<?php

namespace wopan\lib;

abstract class WoPanChannel
{
    public $clientId = '1001000021';
    public $clientSecret = 'XFmi9GS2hzk98jGX';

    public $accessToken = "";

    /**
     * 通道名稱
     * @var String
     */
    public static $channel;

    public function __construct($accessToken)
    {
        $this->accessToken = $accessToken;
    }

    /**
     * @return WoPanResponse
     */
    protected function request($key, $body = [])
    {
        $channel = static::$channel;

        $this->accessToken && $header[] = 'accessToken: ' . $this->accessToken;

        $res = WoPanRequest::send("/{$channel}/dispatcher", [$channel, $key], $body, $header);

        if ($res['STATUS'] !== '200') {
            throw new WoPanException($res['MSG'], $res['STATUS']);
        }

        $code = '0000';
        $msg = 'ok';
        $data = new \stdClass();

        if (isset($res['RSP']) && isset($res['RSP']['RSP_CODE'])) {
            $code = (string)$res['RSP']['RSP_CODE'];
            $msg = (string)$res['RSP']['RSP_DESC'];
            switch ($code) {
                case "1001":
                    // 需要重新登录
                    throw new WoPanException($msg, $code);
                    break;
                case "130015":
                case "8005":
                case "1000":
                case "8001": // 账号未注册或密码错误!
                    throw new WoPanException($msg, $code);
                    break;
                default:
                    break;
            }
            $data = $res['RSP']['DATA'];
        }
        return new WoPanResponse($code, $msg, $data);
    }
}
